﻿using Microsoft.Extensions.Configuration;

namespace DoNet.Common.Helpers
{
    public static class ConfigurationHelper
    {
        /// <summary>
        /// 封装要操作的字符
        /// </summary>
        /// <param name="sections">节点配置</param>
        /// <returns></returns>
        public static string app(this IConfiguration configuration, params string[] sections)
        {
            try
            {
                if (sections.Any())
                {
                    return configuration[string.Join(":", sections)] ?? string.Empty;
                }
            }
            catch (Exception) { }

            return string.Empty;
        }

        /// <summary>
        /// 递归获取配置信息数组
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="sections"></param>
        /// <returns></returns>
        public static List<T> app<T>(this IConfiguration configuration, params string[] sections)
        {
            List<T> list = new List<T>();
            // 引用 Microsoft.Extensions.Configuration.Binder 包
            configuration.Bind(string.Join(":", sections), list);
            return list;
        }

        /// <summary>
        /// 根据路径  configuration["App:Name"];
        /// </summary>
        /// <param name="sectionsPath"></param>
        /// <returns></returns>
        public static string GetValue(this IConfiguration configuration, string sectionsPath)
        {
            try
            {
                if (configuration != null)
                {
                    return configuration[sectionsPath] ?? string.Empty;
                }
            }
            catch (Exception) { }

            return string.Empty;

        }
    }
}
